package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hjq.base.BaseDialog;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;

import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class ControllerReplaceSyncActivity extends AppActivity {
    Boolean isSlave;
    private TextView tvProgressValue;
    private ProgressBar progressBar;
    private String replaceRecordSerialNo;
    private ImageView imgStep2;
    private LinearLayout layoutStep2;
    private TextView tvConfigWifi;
    @Log
    public static void start(Context context, String serialNo, int replaceType, Boolean isSlave) {
        Intent intent = new Intent(context, ControllerReplaceSyncActivity.class);
        intent.putExtra("serialNo", serialNo);
        intent.putExtra("replaceType", replaceType);
        intent.putExtra("isSlave", isSlave);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_controller_replace_sync;
    }

    @Override
    protected void initView() {
        isSlave = getIntent().getBooleanExtra("isSlave",false);
        tvProgressValue = findViewById(R.id.tv_progress);
        progressBar = findViewById(R.id.progress_bar);
        imgStep2 = findViewById(R.id.step_2_check);
        layoutStep2 = findViewById(R.id.step_2_text);
        tvConfigWifi = findViewById(R.id.tv_config_wifi);
        imgStep2.setVisibility(isSlave ? View.GONE : View.VISIBLE);
        layoutStep2.setVisibility(isSlave ? View.GONE : View.VISIBLE);
        tvConfigWifi.setText(isSlave ? "替换" : "配置网络");
    }

    @Override
    protected void initData() {
        setProgressValue(0);
        checkReplace();
    }

    private void setProgressValue(int progressValue){
        tvProgressValue.setText(progressValue + "%");
        progressBar.setProgress(progressValue);
    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;
    private void showFailDialog() {
        if (mConfirmCancelHintDialog ==  null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                finish();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                retryReplace();
                mConfirmCancelHintDialogBuilder.dismiss();
            }
        });
        mConfirmCancelHintDialogBuilder.setHintIcon(R.attr.icon_remind_fail);
        mConfirmCancelHintDialogBuilder.setHint("数据同步失败");
        mConfirmCancelHintDialogBuilder.setRightText("重新同步");
        mConfirmCancelHintDialogBuilder.setContent("网络连接中断，请检查当前网络");
        mConfirmCancelHintDialog.show();
    }

    private BaseDialog successDialog;
    private void showSuccessDialog(){
        successDialog = new ConfirmHintDialog.Builder(this)
                .setHint("数据同步成功")
                .setRightBtnText(getResources().getString(R.string.common_confirm))
                .setHintIcon(R.attr.icon_remind_correct)
                .setListener(new ConfirmHintDialog.OnListener() {
                    @Override
                    public void onLeftClick(BaseDialog dialog) {
                    }

                    @Override
                    public void onConfirm(BaseDialog dialog) {
                        ActivityManager.getInstance().finishActivity(ControllerSettingActivity.class);
                        ActivityManager.getInstance().finishActivity(ControllerDeviceAcitvity.class);
                        ActivityManager.getInstance().finishActivity(LLRegionalGatewayActivity.class);
                        finish();
                    }
                })
                .create();
        //弹出解绑成功
        successDialog.show(3, new BaseDialog.DelayTimeCallBack() {
            @Override
            public void callback(int time) {
                TextView textView = successDialog.getContentView().findViewById(R.id.tv_content);
                textView.setText(String.format(getString(R.string.few_second_try), ""+time));
                if (time == 0){
                    finish();
                }
            }
        });
    }

    private void retryReplace() {
        LLHttpManager.retryControllerReplace(this, replaceRecordSerialNo, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                initData();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private Runnable pollingRunnable = new Runnable(){
        @Override
        public void run() {
            checkReplace();
        }
    };

    private void checkReplace() {
        LLHttpManager.checkControllerReplace(this, getIntent().getIntExtra("replaceType",1), getIntent().getStringExtra("serialNo"), new HttpCallback<HttpData<Map<String,Object>>>(null) {
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<Map<String,Object>> result) {
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                handleFailed();
            }

            @Override
            public void onEnd(Call call) {

            }
        });
    }

    private void handleResult(Map<String,Object> data){
        //发起操作:0 正在操作:1 操作成功:2 操作失败:3 操作异常:4 停止操作:5
        replaceRecordSerialNo = (String) data.get("replaceRecordSerialNo");
        if(data != null){
            int state = new Double((Double) data.get("replaceState")).intValue();
            switch (state){
                case 1:
                case 2:
                case 3:
                    getHandler().postDelayed(pollingRunnable, 1000);
                    int value =  new Double((Double) data.get("stap")).intValue();
                    setProgressValue(value);
                    break;
                case 4:
                case 7:
                    getHandler().removeCallbacksAndMessages(null);
                    refreshControllerData(AppApplication.getInstance().getCurrentHouseSerialNo());
                    break;
                case 5:
                case 6:
                    handleFailed();
                    break;
            }
        }
    }

    private void refreshControllerData(String houseSerialNo) {
        LLHttpManager.getControllers(new ApplicationLifecycle(), houseSerialNo, new HttpCallback<HttpData<List<ControllerBean>>>(this) {
            @Override
            public void onSucceed(HttpData<List<ControllerBean>> result) {

                LLControllerDBManager.getInstance(getContext()).refreshAllControllersTx(result.getData());
                refreshDeviceData(houseSerialNo);
            }

            @Override
            public void onFail(Exception e) {
            }
        });
    }

    private void refreshDeviceData(String houseSerialNo) {
        LLHttpManager.house_getdevices(new ApplicationLifecycle(), houseSerialNo, new HttpCallback<HttpData<List<DeviceBean>>>(this) {
            @Override
            public void onSucceed(HttpData<List<DeviceBean>> result) {
                LLDeviceDBManager.getInstance(getContext()).refreshAllDevicesTx(result.getData(), null);
                showSuccessDialog();
            }

            @Override
            public void onFail(Exception e) {
            }
        });
    }

    private void handleFailed(){
        getHandler().removeCallbacksAndMessages(null);
        showFailDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getHandler().removeCallbacksAndMessages(null);
    }


}
